package org.cjlext.ui;

import org.cjlm.ui.pub.MInternalFrame;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DemoManagerUI extends MInternalFrame {
    // 模拟数据存储
    private final Map<String, Order> orders = new HashMap<>();
    private final Map<String, List<OrderDetail>> orderDetails = new HashMap<>();
    private final Map<String, List<ExecutionRecord>> executions = new HashMap<>();
    private String currentOrderId;

    // UI组件
    private final CardLayout cardLayout = new CardLayout();
    private final JPanel mainPanel = new JPanel(cardLayout);
    private final JTable orderTable;
    private final DefaultTableModel orderTableModel;
    private final JTabbedPane detailTabs = new JTabbedPane();
    private final JTable detailTable;
    private final JTable executionTable;
    private final JButton btnNew = new JButton("新增");
    private final JButton btnEdit = new JButton("修改");
    private final JButton btnDelete = new JButton("删除");
    private final JButton btnQuery = new JButton("查询");
    public DemoManagerUI(String title, boolean max, int width, int height) {
        super(title, max, width, height);
        // 初始化模拟数据
        initSampleData();

        setTitle("销售订单管理系统");
        setSize(1000, 700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//        setLocationRelativeTo(null);

        // 主面板设置
        JPanel contentPane = new JPanel(new BorderLayout(10, 10));
        contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));
        setContentPane(contentPane);

        // 1. 列表界面
        JPanel listPanel = new JPanel(new BorderLayout(10, 10));

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        buttonPanel.add(btnNew);
        buttonPanel.add(btnEdit);
        buttonPanel.add(btnDelete);
        buttonPanel.add(btnQuery);

        // 主表
        String[] orderColumns = {"订单号", "客户", "订单日期", "总金额", "状态"};
        orderTableModel = new DefaultTableModel(orderColumns, 0){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        orderTable = new JTable(orderTableModel);
        orderTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane orderScrollPane = new JScrollPane(orderTable);
        orderScrollPane.setPreferredSize(new  Dimension(0, 200));

        // 子表层叠面板
        detailTabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);

        // 订单明细子表
        String[] detailColumns = {"产品名称", "数量", "单价"};
        DefaultTableModel detailModel = new DefaultTableModel(detailColumns, 0);
        detailTable = new JTable(detailModel);
        detailTable.setEnabled(false);  // 列表界面不可编辑

        // 执行情况子表
        String[] execColumns = {"执行日期", "操作内容", "操作人"};
        DefaultTableModel execModel = new DefaultTableModel(execColumns, 0);
        executionTable = new JTable(execModel);
        executionTable.setEnabled(false);

        detailTabs.addTab(" 订单明细", new JScrollPane(detailTable));
        detailTabs.addTab(" 执行记录", new JScrollPane(executionTable));

        // 组装列表界面
//        listPanel.add(buttonPanel,  BorderLayout.NORTH);
//        listPanel.add(orderScrollPane,  BorderLayout.CENTER);
//        listPanel.add(detailTabs,  BorderLayout.SOUTH);
        JSplitPane splitPane = new JSplitPane(
                JSplitPane.VERTICAL_SPLIT,
                orderScrollPane,
                detailTabs
        );
        splitPane.setResizeWeight(0.6);  // 60%空间给主表，40%给子表
        splitPane.setOneTouchExpandable(true);  // 添加快速折叠按钮

        listPanel.add(buttonPanel,  BorderLayout.NORTH);
        listPanel.add(splitPane,  BorderLayout.CENTER); // 将分割窗格放入CENTER

        // 2. 卡片界面
        JPanel cardPanel = createCardPanel();

        // 添加到主卡片面板
        mainPanel.add(listPanel,  "list");
        mainPanel.add(cardPanel,  "card");
        contentPane.add(mainPanel,  BorderLayout.CENTER);

        // 事件处理
        setupEventHandlers();
        loadOrderData();
    }

    // 数据模型
    private static class Order {
        String orderId;
        String customer;
        String orderDate;
        double totalAmount;
        String status;

        public Order(String orderId, String customer, String orderDate, double totalAmount, String status) {
            this.orderId  = orderId;
            this.customer  = customer;
            this.orderDate  = orderDate;
            this.totalAmount  = totalAmount;
            this.status  = status;
        }
    }

    private static class OrderDetail {
        String product;
        int quantity;
        double unitPrice;

        public OrderDetail(String product, int quantity, double unitPrice) {
            this.product  = product;
            this.quantity  = quantity;
            this.unitPrice  = unitPrice;
        }
    }

    private static class ExecutionRecord {
        String execDate;
        String action;
        String operator;

        public ExecutionRecord(String execDate, String action, String operator) {
            this.execDate  = execDate;
            this.action  = action;
            this.operator  = operator;
        }
    }

    private JPanel createCardPanel() {
        JPanel cardPanel = new JPanel(new BorderLayout(10, 10));

        // 顶部按钮
        JPanel cardButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JButton btnBack = new JButton("返回列表");
        JButton btnEditCard = new JButton("修改");
        cardButtonPanel.add(btnBack);
        cardButtonPanel.add(btnEditCard);

        // 主表详情区域
        JPanel orderInfoPanel = new JPanel(new GridLayout(0, 2, 10, 10));
        orderInfoPanel.setBorder(BorderFactory.createTitledBorder(" 订单信息"));
        String[] fields = {"订单号：", "客户：", "订单日期：", "总金额：", "状态："};
        Map<String, JTextField> cardFields = new HashMap<>();

        for (String field : fields) {
            JLabel label = new JLabel(field);
            JTextField textField = new JTextField(20);
            textField.setEditable(false);
            orderInfoPanel.add(label);
            orderInfoPanel.add(textField);
            cardFields.put(field.replace(" ：", ""), textField);
        }

        // 子表层叠面板（与列表界面相同实例）
        JTabbedPane cardTabs = new JTabbedPane();
        cardTabs.addTab(" 订单明细", new JScrollPane(detailTable));
        cardTabs.addTab(" 执行记录", new JScrollPane(executionTable));

        // 组装卡片界面
//        cardPanel.add(cardButtonPanel,  BorderLayout.NORTH);
//        cardPanel.add(orderInfoPanel,  BorderLayout.CENTER);
//        cardPanel.add(cardTabs,  BorderLayout.SOUTH);
        JSplitPane splitPane = new JSplitPane(
                JSplitPane.VERTICAL_SPLIT,
                orderInfoPanel,
                cardTabs
        );
        splitPane.setResizeWeight(0.6);  // 60%空间给主表，40%给子表
        splitPane.setOneTouchExpandable(true);  // 添加快速折叠按钮

        cardPanel.add(cardButtonPanel,  BorderLayout.NORTH);
        cardPanel.add(splitPane,  BorderLayout.CENTER); // 将分割窗格放入CENTER

        // 卡片界面事件
        btnBack.addActionListener(e  -> cardLayout.show(mainPanel,  "list"));
        btnEditCard.addActionListener(e  -> switchToEditMode(cardFields));

        return cardPanel;
    }

    private void setupEventHandlers() {
        // 主表选择事件
        orderTable.getSelectionModel().addListSelectionListener(e  -> {
            if (!e.getValueIsAdjusting())  {
                int row = orderTable.getSelectedRow();
                if (row >= 0) {
                    currentOrderId = (String) orderTableModel.getValueAt(row,  0);
                    loadSubTableData();
                }
            }
        });

        // 双击跳转卡片
        orderTable.addMouseListener(new  MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount()  == 2) {
                    int row = orderTable.rowAtPoint(e.getPoint());
                    if (row >= 0) {
                        currentOrderId = (String) orderTableModel.getValueAt(row,  0);
                        cardLayout.show(mainPanel,  "card");
                        // 这里应加载卡片数据（实际开发中实现）
                    }
                }
            }
        });

        // 按钮事件
        btnNew.addActionListener(e  -> {
            // 实际开发中实现新增逻辑
            JOptionPane.showMessageDialog(this,  "新增订单功能");
        });

        btnEdit.addActionListener(e  -> {
            if (currentOrderId != null) {
                // 实际开发中跳转到编辑界面
                JOptionPane.showMessageDialog(this,  "编辑订单: " + currentOrderId);
            } else {
                JOptionPane.showMessageDialog(this,  "请先选择订单");
            }
        });

        btnDelete.addActionListener(e  -> {
            if (currentOrderId != null) {
                int confirm = JOptionPane.showConfirmDialog(this,
                        "确定删除订单 " + currentOrderId + "?", "确认删除", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    // 实际开发中实现删除逻辑
                    orders.remove(currentOrderId);
                    orderDetails.remove(currentOrderId);
                    executions.remove(currentOrderId);
                    loadOrderData();
                    currentOrderId = null;
                }
            }
        });

        btnQuery.addActionListener(e  -> {
            // 实际开发中实现查询弹窗
            JOptionPane.showInputDialog(this,  "输入查询条件：");
        });
    }

    private void loadOrderData() {
        orderTableModel.setRowCount(0);
        for (Order order : orders.values())  {
            orderTableModel.addRow(new  Object[]{
                    order.orderId,
                    order.customer,
                    order.orderDate,
                    order.totalAmount,
                    order.status
            });
        }
    }

    private void loadSubTableData() {
        if (currentOrderId != null) {
            // 加载明细数据
            DefaultTableModel detailModel = (DefaultTableModel) detailTable.getModel();
            detailModel.setRowCount(0);
            List<OrderDetail> details = orderDetails.getOrDefault(currentOrderId,  new ArrayList<>());
            for (OrderDetail detail : details) {
                detailModel.addRow(new  Object[]{
                        detail.product,
                        detail.quantity,
                        detail.unitPrice
                });
            }

            // 加载执行记录
            DefaultTableModel execModel = (DefaultTableModel) executionTable.getModel();
            execModel.setRowCount(0);
            List<ExecutionRecord> records = executions.getOrDefault(currentOrderId,  new ArrayList<>());
            for (ExecutionRecord record : records) {
                execModel.addRow(new  Object[]{
                        record.execDate,
                        record.action,
                        record.operator
                });
            }
        }
    }

    private void switchToEditMode(Map<String, JTextField> fields) {
        // 实际开发中实现编辑模式切换
        for (JTextField field : fields.values())  {
            field.setEditable(true);
            field.setBackground(Color.WHITE);
        }
        detailTable.setEnabled(true);
        executionTable.setEnabled(true);
    }

    private void initSampleData() {
        // 添加模拟数据
        Order order1 = new Order("SO2025001", "客户A", "2025-06-01", 15000.0, "已发货");
        Order order2 = new Order("SO2025002", "客户B", "2025-06-05", 8900.0, "已付款");

        orders.put(order1.orderId,  order1);
        orders.put(order2.orderId,  order2);

        // 订单明细
        List<OrderDetail> details1 = new ArrayList<>();
        details1.add(new  OrderDetail("产品X", 2, 5000.0));
        details1.add(new  OrderDetail("产品Y", 5, 1000.0));
        orderDetails.put(order1.orderId,  details1);

        List<OrderDetail> details2 = new ArrayList<>();
        details2.add(new  OrderDetail("产品Z", 3, 2500.0));
        details2.add(new  OrderDetail("产品W", 2, 700.0));
        orderDetails.put(order2.orderId,  details2);

        // 执行记录
        List<ExecutionRecord> exec1 = new ArrayList<>();
        exec1.add(new  ExecutionRecord("2025-06-03", "订单审核", "张三"));
        exec1.add(new  ExecutionRecord("2025-06-05", "发货处理", "李四"));
        executions.put(order1.orderId,  exec1);

        List<ExecutionRecord> exec2 = new ArrayList<>();
        exec2.add(new  ExecutionRecord("2025-06-06", "订单确认", "王五"));
        executions.put(order2.orderId,  exec2);
    }

    @Override
    public String getDefaultTile() {
        return null;
    }
}
